﻿using System.Reflection;
using Yto.Common.Dependency;
using Yto.EF.DbCtx;
using Yto.EF.Repositories;
using Yto.Modules;
using Yto.Reflection;
using Yto.Repositories;
using Yto.Unitwork;

namespace Yto.EF
{
    [Depends(typeof(UnitModule))]
    public class EFModule : BaseModule
    {
        private ITypeFinder _typeFinder;

        public EFModule(ITypeFinder typeFinder)
        {
            _typeFinder = typeFinder;
        }
        public override void Initialize()
        {
            CtnManager.RegistAssembly(Assembly.GetExecutingAssembly());
            CtnManager.Regist(typeof(IDbProvider<>), typeof(DbProvider<>), RegisterLifeStyle.Transient);
            RegistRepositories();
        }

        private void RegistRepositories()
        {
            var DbcontextTypes = _typeFinder.FindByCondition(
                x => x.IsPublic
                && !x.IsAbstract
                && x.IsClass
                && typeof(BaseDbContext).IsAssignableFrom(x)
            );
            foreach (var item in DbcontextTypes)
            {
                CtnManager.Resolver<IRegistRepositories>().RegistRepository(item, typeof(EFRepository<,>), typeof(EFRepository<,,>));
            }

        }
    }
}
